package tool;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.dao.AbstractMapperDAO;

public class MapperGenerator {
    private static String RESOURCE = "mybatis.xml";
    private static InputStream STREAM;
    private static SqlSessionFactory FACTORY;

    @SuppressWarnings("unchecked")
    public static <T extends AbstractMapperDAO> T generate(Class<T> clazz)
        throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
        try {
            STREAM = Resources.getResourceAsStream(RESOURCE);
            FACTORY = new SqlSessionFactoryBuilder().build(STREAM);
            Class<?>[] interfaces = FACTORY.getClass().getInterfaces();
            for (Class<?> clazz1 : interfaces) {
                if (clazz1.equals(SqlSessionFactory.class)) {
                    Constructor<? extends AbstractMapperDAO> constructor = clazz.getConstructor(clazz1);
                    return (T) constructor.newInstance(FACTORY);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
